import Cocoa
import FlutterMacOS

class MainFlutterWindow: NSWindow {

  // UserDefaults keys for saving window state
  private let windowFrameKey = "MainWindowFrame"

  override func awakeFromNib() {
    let flutterViewController = FlutterViewController()
    let windowFrame = self.frame
    self.contentViewController = flutterViewController
    self.setFrame(windowFrame, display: true)

    RegisterGeneratedPlugins(registry: flutterViewController)

    super.awakeFromNib()

    // 隐藏标题栏，启用全尺寸内容视图
    self.titleVisibility = .hidden
    self.titlebarAppearsTransparent = true
    self.styleMask.insert(.fullSizeContentView)

    // Restore window frame from last session
    restoreWindowFrame()

    // Setup window delegate to save frame on close
    self.delegate = self
  }

  /// Restore window frame and position from UserDefaults
  private func restoreWindowFrame() {
    if let frameString = UserDefaults.standard.string(forKey: windowFrameKey) {
      let savedFrame = NSRectFromString(frameString)

      // Ensure the saved frame is still valid on current screen configuration
      if isFrameValid(savedFrame) {
        self.setFrame(savedFrame, display: true, animate: false)
      }
    }
  }

  /// Save current window frame to UserDefaults
  private func saveWindowFrame() {
    let frameString = NSStringFromRect(self.frame)
    UserDefaults.standard.set(frameString, forKey: windowFrameKey)
    UserDefaults.standard.synchronize()
  }

  /// Check if the frame is still valid on current screen configuration
  private func isFrameValid(_ frame: NSRect) -> Bool {
    // Check if the frame intersects with any available screen
    for screen in NSScreen.screens {
      if screen.visibleFrame.intersects(frame) {
        return true
      }
    }
    return false
  }
}

// MARK: - NSWindowDelegate
extension MainFlutterWindow: NSWindowDelegate {

  /// Save window frame when window moves
  func windowDidMove(_ notification: Notification) {
    saveWindowFrame()
  }

  /// Save window frame when window resizes
  func windowDidResize(_ notification: Notification) {
    saveWindowFrame()
  }

  /// Save window frame before closing
  func windowWillClose(_ notification: Notification) {
    saveWindowFrame()
  }
}
